import React from 'react'
import { Button, Toast, InputItem } from 'antd-mobile'
import { APPID } from '../../constants'
import getQuery from '../../helpers/getQuery'
import { createForm } from 'rc-form';
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import { actions as userActionCraetors } from '../../redux/modules/user'
import config from '../../../config';
import './index.less';

class Login extends React.PureComponent {

  static contextTypes = {
    router: React.PropTypes.object.isRequired
  }

  state = {
    userCode: '',
    password: '',
    jsCode: ''
  }

  componentDidMount() {
    let code = getQuery('code')
    if (code) {
      this.setState({
        jsCode: code
      })
    } else {
      this.handleLogin()
    }
  }

  render() {
    const { getFieldProps } = this.props.form;
    return <section className="inner-page login-page">
      <div className="logo"></div>
      <div className="title">港口物流智慧平台</div>
      <InputItem
        {...getFieldProps('userCode', {
          initialValue: this.state.userCode,
        })}
        clear
        autoCapitalize="off"
        ref={instantce => this.inputRef = instantce}
        onChange={this.handleChange.bind(this, 'userCode')}
        onBlur={this.handleBlur.bind(this)}
        placeholder="请输入帐号"
      ><i className="iconfont icon-zhanghao" /></InputItem>
      <InputItem
        {...getFieldProps('password', {
          initialValue: this.state.password,
        })}
        clear
        type="password"
        onBlur={this.handleBlur.bind(this)}
        autoCapitalize="off"
        onChange={this.handleChange.bind(this, 'password')}
        placeholder="请输入密码"
      ><i className="iconfont icon-mima" /></InputItem>
      <Button type="primary" onClick={this.handleSubmit.bind(this)}>登录</Button>
    </section>
  }

  handleBlur() {
    window.scroll(0,0); //让页面归位
  }

  handleChange(field, value) {
    this.setState({
      [field]: value
    })
  }

  handleSubmit() {
    this.props.actions.login(this.state, json => {
      if (json.IsSuccess) {
        sessionStorage.setItem('token', json.Data.Token)
        this.context.router.push(`${config.rootAlias}/list`)
      } else {
        Toast.fail(json.Msg || '服务异常', 1)
      }
    })
  }

  handleLogin() {
    const REDIRECT_URI = window.location.href;
    const SCOPE = "snsapi_base" //'snsapi_userinfo' 
    const STATE = '1'
    this.props.actions.getAppid(json => {
      if (json.IsSuccess) {
        const codeUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${json.Data.Value}&redirect_uri=${REDIRECT_URI}&response_type=code&scope=${SCOPE}&state=${STATE}#wechat_redirect`
        window.location.replace(codeUrl)
      }
    })
  }
}

const stateToProps = state => ({
  ...state.data
})

const dispatchToProps = dispatch => ({
  actions: bindActionCreators(userActionCraetors, dispatch)
})

export default connect(stateToProps, dispatchToProps)(createForm()(Login));
